//
//  BookShelfViewController.m
//  handbooklite
//
//  Created by bao_wsfk on 12-8-29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BookShelfViewController.h"
#import "DownloadView.h"
#import "JSONKit.h"
#import "DownNumFileUtil.h"
#import "BooksFileUtil.h"
#import "BookCellView.h"
#import "BookViewController.h"
#import "SSZipArchive.h"

@interface BookShelfViewController ()

@end

@implementation BookShelfViewController

@synthesize networkQueue =_networkQueue;
@synthesize books_path =_books_path;
@synthesize progress =_progress;
@synthesize downnums =_downnums;
@synthesize books =_books;
@synthesize gridView =_gridView;
//@synthesize pageControl =_pageControl;
@synthesize myWindow =_myWindow;
@synthesize bundleBookPath =_bundleBookPath;
@synthesize docBookPath =_docBookPath;
@synthesize defaultScreeshotsPath =_defaultScreeshotsPath;

#define BOOK_CELL_NUMBER 5
#define BOOKS_DIRECTOR @"books"
#define SCREENSHOT_DIRECTOR @"wsyd-screenshots"

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title =@"免费版";
    }
    return self;
}

- (void)viewDidLoad
{
    //注册下载通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(download:)
                                                 name:@"download"
                                               object:nil];
    self.books_path =[DOCUMENT_PATH stringByAppendingPathComponent:BOOKS_DIRECTOR];
    self.bundleBookPath =[RESOURCE_PATH stringByAppendingPathComponent:BOOKS_DIRECTOR];
    self.docBookPath =[DOCUMENT_PATH stringByAppendingPathComponent:BOOKS_DIRECTOR];
    self.defaultScreeshotsPath =[CACHE_PATH stringByAppendingPathComponent:SCREENSHOT_DIRECTOR];
    
    NSArray * windows =[UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if ([window isKindOfClass:[InterceptorWindow class]]) {
            self.myWindow =(InterceptorWindow *)window;
            [_myWindow setDisableTap:YES];
        }
    }
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"nav_bg.png"]]];
    [self updateBooks];
    [self setUpMMGridView];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.networkQueue =nil;
    self.books_path =nil;
    self.books =nil;
    self.downnums =nil;
    [self.myWindow release],self.myWindow =nil;
    self.bundleBookPath =nil;
    self.docBookPath =nil;
    self.defaultScreeshotsPath =nil;
    self.gridView =nil;    
    //self.pageControl =nil;
    self.progress =nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return [self orientationByString:ORIENTATION InterfaceOrientation:interfaceOrientation] ;
}


//列表
#pragma - MMGridViewDataSource

- (NSInteger)numberOfCellsInGridView:(MMGridView *)gridView
{
    return ([_books count]%BOOK_CELL_NUMBER)>0?
    [_books count]+(BOOK_CELL_NUMBER-([_books count]%BOOK_CELL_NUMBER)):[_books count]+5;
}

#pragma - MMGridViewDataSource
- (MMGridViewCell *)gridView:(MMGridView *)gridView cellAtIndex:(NSUInteger)index
{
    BookCellView *cell = [[[BookCellView alloc] initWithFrame:CGRectNull] autorelease];
    [cell setIsClick:YES];
    
    if ((index+1) >[_books count]) {
        cell.title.text = [NSString stringWithFormat:@"当前没有手册"];
        cell.backgroundView.backgroundColor = [UIColor grayColor];
    }else {
        NSDictionary *bookDic =[self bookByDownNum:[_downnums objectAtIndex:index]];
        NSString *iconPath =[self.books_path stringByAppendingPathComponent:[bookDic objectForKey:@"icon"]];
        NSString *bookTitle =[bookDic objectForKey:@"name"];
        cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:
                                               [UIImage imageWithContentsOfFile:iconPath]];
        [cell.title setText:bookTitle];
    }
    
    return cell;
}

// ----------------------------------------------------------------------------------

#pragma - MMGridViewDelegate

- (void)gridView:(MMGridView *)gridView didSelectCell:(MMGridViewCell *)cell atIndex:(NSUInteger)index
{
    //[(BookCellView *)cell startProgress];
    CCLog(@"----------index:%i",index);
    //判断当前点击的是否存在手册
    if ((index+1)>[self.books count]) {
        CCLog(@"--------当前没有手册 进入下载");
        [self toDownloadViewByBookCell:cell];
    }else {
        CCLog(@"-------有手册 进入手册观看");
        [self toBookViewController:index];
    }
    
}

#pragma - MMGridViewDelegate
- (void)gridView:(MMGridView *)gridView didDoubleTapCell:(MMGridViewCell *)cell atIndex:(NSUInteger)index
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:[NSString stringWithFormat:@"Cell at index %d was double tapped.", index]
                                                   delegate:nil 
                                          cancelButtonTitle:@"Cool!" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

#pragma - MMGridViewDelegate
- (void)gridView:(MMGridView *)theGridView changedPageToIndex:(NSUInteger)index
{
    NSLog(@"----------changedPageToIndex:%i",index);
}

//初始化MMGridView
- (void)setUpMMGridView{
    self.gridView.cellMargin = 30;
    self.gridView.numberOfRows = BOOK_CELL_NUMBER;
    self.gridView.numberOfColumns = 3;
    //self.gridView.layoutStyle = HorizontalLayout;
    self.gridView.layoutStyle = VerticalLayout;
}

- (void)toDownloadViewByBookCell:(MMGridViewCell *)bookCell{
    DownloadView *downView =[[DownloadView alloc]initWithNibName:@"DownloadView" bundle:nil];
    [downView setBookCell:bookCell];
    [self.navigationController pushViewController:downView animated:YES];
    [downView release];
}

//下载
- (void)download:(NSNotification *)notification{
    NSDictionary *book =[notification object];
    CCLog(@"------start download book:%@",book);
    BookCellView *cell =(BookCellView *)[book objectForKey:@"bookcell"];
    [cell setIsClick:NO];
    [self initNetworkQueueByProgress:[cell startProgress]];
    //下载icon
    ASIHTTPRequest *request_icon =[ASIHTTPRequest 
                                   requestWithURL:
                                   [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",
                                                         BASE_URL,[book objectForKey:@"icon"]]]];
    
    NSString *saveIconPath =[_books_path stringByAppendingPathComponent:@"icons"];
    [self createPath:saveIconPath];
    [request_icon setDownloadDestinationPath:[saveIconPath stringByAppendingPathComponent:
                                              [[book objectForKey:@"icon"]
                                               lastPathComponent]]];
    NSMutableDictionary *request_icon_info =[[NSMutableDictionary alloc]init];
    [request_icon_info setObject:@"download_icon" forKey:@"name"];
    [request_icon_info setObject:book forKey:@"book"];
    [request_icon_info setObject:cell forKey:@"bookcell"];
    [request_icon setUserInfo:request_icon_info];
    [request_icon setTimeOutSeconds:5];
    [request_icon setShouldAttemptPersistentConnection:NO];
    [_networkQueue addOperation:request_icon];
    [request_icon_info release];
    
    //下载zip
    ASIHTTPRequest *request_zip =[ASIHTTPRequest 
                                   requestWithURL:
                                  [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",
                                                        BASE_URL,[book objectForKey:@"zip"]]]];
    
    NSString *saveZipPath =[_books_path stringByAppendingPathComponent:@"zips"];
    [self createPath:saveZipPath];
    [request_zip setDownloadDestinationPath:[saveZipPath stringByAppendingPathComponent:
                                             [[book objectForKey:@"zip"]
                                              lastPathComponent]]];
    NSMutableDictionary *request_zip_info =[[NSMutableDictionary alloc]init];
    [request_zip_info setObject:@"download_zip" forKey:@"name"];
    [request_zip_info setObject:book forKey:@"book"];
    [request_zip_info setObject:cell forKey:@"bookcell"];
    [request_zip setUserInfo:request_zip_info];
    [request_zip setTimeOutSeconds:10];
    [request_zip setShouldAttemptPersistentConnection:NO];
    [_networkQueue addOperation:request_zip];
    [request_zip_info release];
    [_networkQueue go];
    
}

- (void)initNetworkQueueByProgress:(UIProgressView *)progress{
    if (!_networkQueue) {
        _networkQueue =[[ASINetworkQueue alloc] init];
    }
    _networkQueue =[[ASINetworkQueue alloc] init];
    [_networkQueue reset];
    [_networkQueue setQueueDidFinishSelector:@selector(didQueueFinished:)];
    [_networkQueue setRequestDidFailSelector:@selector(didDownloadFailed:)];
    [_networkQueue setRequestDidFinishSelector:@selector(didDownloadFinished:)];
    [_networkQueue setMaxConcurrentOperationCount:2];
    [_networkQueue setDelegate:self];
}

//刷新手册列表
- (void)updateBooks{
    if (_downnums) {
        [_downnums removeAllObjects],[_downnums release],_downnums =nil;
    }
    if (!_books) {
        [_books removeAllObjects],[_books release],_books =nil;
    }
    //初始化数据
    DownNumFileUtil *dfu =[DownNumFileUtil newInstance];
    _downnums =[[dfu downNums] mutableCopy];
    
    BooksFileUtil *bfu =[BooksFileUtil newInstance];
    _books =[[bfu books] mutableCopy];
    
    CCLog(@"------downnums:%@\n----books:%@",_downnums,_books);
}

//观看
- (void)toBookViewController:(int)index{

    NSDictionary *bookDic =[self bookByDownNum:[self.downnums objectAtIndex:index]];
    
    NSString *bookDocPath = [_docBookPath stringByAppendingPathComponent:(NSString *)[bookDic objectForKey:@"dir"]];
    NSString *bookBundlePath = [_bundleBookPath stringByAppendingPathComponent:(NSString *)[bookDic objectForKey:@"dir"]];
    
    BookViewController *bookViewController = [[BookViewController alloc]
                          initWithDocumentsBookPath:bookDocPath
                          bundleBookPath:bookBundlePath
                          defaultScreeshotsPath:[_defaultScreeshotsPath stringByAppendingPathComponent:(NSString *)[bookDic objectForKey:@"dir"]]];
    [_myWindow setDisableTap:NO];
    [_myWindow setTarget:[bookViewController scrollView] eventsDelegate:bookViewController];
    
//    [bookViewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
//    
//    //不用push  因为push切换界面后 界面的方向旋转总是有问题
//    // Check if iOS4 or 5
//    if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]) {
//        // iOS 5
//        [self presentViewController:bookViewController animated:YES completion:nil];
//    } else {
//        // iOS 4
//        [self presentModalViewController:bookViewController animated:YES];
//    }
    [bookViewController setTitle:[bookDic objectForKey:@"name"]];
    [self.navigationController pushViewController:bookViewController animated:YES];
    //由于这两个方法暂时不知道为什么不能执行 现在使用通知的方式执行它们
    [[NSNotificationCenter defaultCenter] postNotificationName:@"willRotate" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didRotate" object:nil];
    
    [bookViewController release];
    
    
}

- (NSDictionary *)bookByDownNum:(NSString *)downnum{
    
    for (NSDictionary *book in self.books) {
        /**
         ["123":{"icon":"icon.jpg","name","时尚家居","dir":"123"}]
         */
        if ([book objectForKey:downnum] !=nil) {
            return [book objectForKey:downnum];
        }
    }
    return nil;
}

//队列下载完成
- (void)didQueueFinished:(ASINetworkQueue *)queue{
    CCLog(@"-------queue finished");
    [_networkQueue reset];
    [_networkQueue release],_networkQueue =nil;
}

//下载失败
- (void)didDownloadFailed:(ASIHTTPRequest *)request{
    NSDictionary *userinfo =[request userInfo];
    
    if ([@"download_icon" isEqualToString:[userinfo objectForKey:@"name"]]) {
        CCLog(@"-------icon download Failed");
    }
    if ([@"download_zip" isEqualToString:[userinfo objectForKey:@"name"]]) {
        CCLog(@"-------zip download Failed");
        [self showMessage:[NSString stringWithFormat:@"%@\n下载失败\n请重新下载",
                           [(NSDictionary *)[userinfo objectForKey:@"book"] objectForKey:@"name"]]];
    }
}
//下载成功
- (void)didDownloadFinished:(ASIHTTPRequest *)request{
    NSDictionary *userinfo =[request userInfo];
    
    if ([@"download_icon" isEqualToString:[userinfo objectForKey:@"name"]]) {
        CCLog(@"-------icon download finished");
    }
    if ([@"download_zip" isEqualToString:[userinfo objectForKey:@"name"]]) {
        CCLog(@"-------zip download finished");
        NSDictionary *book =[userinfo objectForKey:@"book"];
        [self showMessage:[NSString stringWithFormat:@"%@\n下载成功\n欢迎您的使用",
                           [book objectForKey:@"name"]]];
        //将下载码存入downnum.json文件中
        DownNumFileUtil *dfu =[DownNumFileUtil newInstance];
        [dfu addDownNum:(NSString *)[book objectForKey:@"downnum"]];
        
        BooksFileUtil *bfu =[BooksFileUtil newInstance];
        [bfu addBooksName:[book objectForKey:@"name"]
                      icon:[[book objectForKey:@"icon"]lastPathComponent]
                   downnum:[book objectForKey:@"downnum"]];
        
        //解压zip 解压后的文件夹名称以下载码命名
        NSString *toBookPath =[self.books_path stringByAppendingPathComponent:[book objectForKey:@"downnum"]];
        BOOL isOk =[SSZipArchive unzipFileAtPath:request.downloadDestinationPath
                                   toDestination:toBookPath
                                       overwrite:YES
                                        password:nil
                                           error:nil];
        if (!isOk) {
            CCLog(@"-------%@解压失败",request.downloadDestinationPath);
        }
        BookCellView *cell =(BookCellView *)[book objectForKey:@"bookcell"];
        [cell setIsClick:YES];
        [cell endProgress];
        [self updateBooks];
        [_gridView reloadData];
    }
}

//判断目录是否存在 如果不存在创建
- (void)createPath:(NSString *)path{
    NSFileManager *fm =[NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        BOOL result =[fm createDirectoryAtPath:path 
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:nil];
        if (!result) {
            CCLog(@"------create %@:failed",path);
        }
    }
}


@end
